import { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, Row, Col, message } from "antd";
import { Base64 } from "js-base64";
import CommonModal from "@/components/CommonModal";
import CommonLoading from "@/components/CommonLoading";
import { getCode } from "@/services/user";
import { layout2 } from "@/utils/config";
import { getDifferUserDetails } from "@/utils/authority";
import { loadScript, getSearchParamsObj, testNotProdEnv } from "@/utils/utils.jsx";
import { bindingUnbindingVxOp } from "../../service";

// let wxAuthParams;
const obj = {
	url: window.location.href,
	industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
	jsoUrl: `${API_SERVER || "https://blade-gateway.test3.zhaojiafang.com"}/blade-user`
};

let unionid;
export default ({ location, wxAuthParams, newUserDetail, handleOk, handleCancel }) => {
	const [form] = Form.useForm();

	const [loading, setLoading] = useState(false);
	const [step, setStep] = useState(1);
	const [count, setCount] = useState(0);
	const navigate = useNavigate();
	const personageMessage = useMemo(() => {
		return getDifferUserDetails();
	}, []);

	useEffect(() => {
		if (count) {
			setTimeout(() => {
				setCount(count - 1);
			}, 1000);
		}
	}, [count]);

	useEffect(() => {
		const obj = getSearchParamsObj(location.search);
		if (obj.unionid) {
			unionid = obj.unionid;
			navigate("/account/safety", { replace: true });
			return;
		}
		if (!newUserDetail?.unionid) {
			setStep(2);
		}
	}, []);

	useEffect(() => {
		if (step == 2) {
			if (window.WxLogin) {
				initQrcodeFunc();
			} else {
				loadScript(`https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js`).then(() => {
					console.log("载入成功");
					window.WxLogin && initQrcodeFunc();
				});
			}
		}
	}, [step]);

	const initQrcodeFunc = async () => {
		const { appId, redirectUri } = wxAuthParams;
		new WxLogin({
			appid: appId,
			self_redirect: false,
			id: "wxbind_container",
			scope: "snsapi_login",
			redirect_uri: encodeURIComponent(redirectUri),
			state: Base64.encode(encodeURIComponent(JSON.stringify(obj))),
			href: `${window.location.hostname == "localhost" ? "http" : "https"}://${window.location.host}/static/wxQrcode.css`
		});
		if (!testNotProdEnv) {
			//只保证生产样式为小码
			setTimeout(() => {
				document.getElementById("wxbind_container").getElementsByTagName("iframe")[0].style.height = "300px";
			});
		}
	};

	const onGetCaptcha = async () => {
		setCount(59);
		setLoading(true);
		const res = await getCode({
			mobile: personageMessage.mobile,
			type: newUserDetail.unionid ? 16 : 15,
			appType: newUserDetail.unionid ? undefined : 2
		});
		if (res.success) {
			message.success("验证码发送成功！");
		}
		setLoading(false);
	};

	const onOk = () => {
		form.validateFields().then(async value => {
			setLoading(true);
			const { code } = value;
			const { success, msg = "操作成功" } = await bindingUnbindingVxOp({
				code,
				mobile: personageMessage.mobile,
				type: newUserDetail.unionid ? 2 : 1,
				unionid: newUserDetail.unionid || unionid,
				industrialBeltFlag: INDUSTRIAL_BELT_FLAG
			});
			if (success) {
				message.success(msg);
				handleOk();
			}
			setLoading(false);
		});
	};

	return (
		<>
			<CommonModal
				title={`微信${newUserDetail?.unionid ? "解绑" : "绑定"}`}
				visible={true}
				width={458}
				onCancel={handleCancel}
				footer={
					step == 1
						? [
								<Button onClick={handleCancel} key="cancel">
									取消
								</Button>,
								<Button type="primary" onClick={onOk} key="ok">
									确定
								</Button>
							]
						: null
				}
			>
				{step == 1 ? (
					<Form name="updatePwd" form={form} {...layout2}>
						<Row>
							<Col span={5} style={{ textAlign: "right" }}>
								账号名：
							</Col>
							<Col span={19}>{personageMessage.account}</Col>
						</Row>
						<Row style={{ margin: "12px 0" }}>
							<Col span={5} style={{ textAlign: "right" }}>
								手机号：
							</Col>
							<Col span={19}>{personageMessage.mobile}</Col>
						</Row>
						<Form.Item
							label="手机验证"
							name="code"
							rules={[
								{
									required: true,
									message: "请输入手机验证码!"
								}
							]}
						>
							<Row gutter={8}>
								<Col span={15}>
									<Input placeholder="请输入验证码" />
								</Col>
								<Col span={8}>
									<Button style={{ width: "115px" }} disabled={count} onClick={onGetCaptcha}>
										{count ? `${count}s` : "获取验证码"}
									</Button>
								</Col>
							</Row>
						</Form.Item>
					</Form>
				) : (
					<div id="wxbind_container" style={{ display: "flex", justifyContent: "center" }}></div>
				)}

				<CommonLoading loading={loading} />
			</CommonModal>
		</>
	);
};
